

//单链表节点
class ListNode {
    public int val;
    public ListNode next;

    public ListNode(int val) {
        this.val = val;
    }

    public ListNode(int val,ListNode next) {
        this.val = val;
        this.next = next;
    }
}

//双链表节点
class DoubleListNode {
    public int val;
    public DoubleListNode next;
    public DoubleListNode pre;

    public DoubleListNode(int val) {
        this.val = val;
        this.next=this.pre=null;
    }

    public DoubleListNode(int val,DoubleListNode next,DoubleListNode pre) {
        this.val = val;
        this.next = next;
        this.pre = pre;
    }
}


public class LinkedListInversion {
    public static void main(String[] args) {
        //创建单链表
        ListNode p1 = new ListNode(1);
        ListNode p2 = new ListNode(2);
        ListNode p3 = new ListNode(3,null);
        p1.next=p2;
        p2.next=p3;
        //单链表反转
        ListNode newp = ListNodeReverse(p1);

        //创建双链表
        DoubleListNode dp1 = new DoubleListNode(1);
        DoubleListNode dp2 = new DoubleListNode(2);
        DoubleListNode dp3 = new DoubleListNode(3);
        dp1.next = dp2;  dp2.pre = dp1;
        dp2.next = dp3;  dp3.pre = dp2;
        System.out.println();
        //双链表反转
        DoubleListNode newdp=DoubleListNodeReverse(dp1);

        System.out.println();
    }
    //单链表反转
    public static ListNode ListNodeReverse(ListNode head) {
        ListNode next = null;
        ListNode pre = null;

        while(head != null) {
            next = head.next;
            head.next = pre;
            pre = head;
            head = next;
        }
        return pre;
    }


    //双链表反转
    public static DoubleListNode DoubleListNodeReverse(DoubleListNode head) {
        DoubleListNode next = null;
        DoubleListNode pre = null;

        while(head != null) {
            next = head.next;
            head.next = pre;
            head.pre = pre;
            pre = head;
            head = next;
        }
        return pre;
    }
}

